package com.Algorithen;
/**
 * 二分查找非递归实现
 * @author 骄傲的大树
 *
 */
public class BinarySeachNoRecur {

	public static void main(String[] args) {
		int[] arr = {1,2,3,4,6,7,8,9,10};
		System.out.println(binarySearch(arr,1));
		
		System.out.println(binarySearch(arr,5));
		System.out.println(binarySearch(arr,10));
		System.out.println(binarySearch(arr,6));

	}
	/**
	 * 
	 * @param arr 查找有序数组
	 * @param target 目标数
	 * @return 有返回位置，否则返回-1
	 */
	public static int binarySearch(int[] arr,int target){
		int left = 0;
		int right = arr.length - 1;
		while(left <= right){
			int mid = (left + right) / 2;
			if(arr[mid] == target){
				return mid;
			}else if(arr[mid] > target){
				right = mid - 1;
			}else{
				left = mid + 1;
			}
		}
		return -1;
	}
}
